﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.UnifyShow.Business;
using Microsoft.Practices.Unity;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class SystemManagementController : BaseController
    {

        private IUser_X user_x;
        private IDevice device;
        private IPerformance performance;
        private IAlert alert;

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user_x).Dispose();
            ((IDisposable)device).Dispose();
            ((IDisposable)performance).Dispose();
            ((IDisposable)alert).Dispose();
        }

        [InjectionConstructor]
        public SystemManagementController(IUser_X _user_x, IDevice _device, IPerformance _performance, IAlert _alert)
        {
            user_x = _user_x;
            device = _device;
            performance = _performance;
            alert = _alert;
        }


        public ActionResult Index()
        {
            SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            return View();

        }


        public ActionResult GetBusinessList()
        {
            //get user info
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var sites = user_x.GetSiteBranchByID(USER_X.ID);
            JsonCollection collection = new JsonCollection();

            //我的设备
            var mydevices = device.GetMyDevices(USER_X.ID);
            JsonObject mydevicefolder = new JsonObject();
            mydevicefolder.MergeProperty("text", new JsonConstant("我的设备"));
            JsonCollection mydeviceChildren = new JsonCollection();
            mydevicefolder.MergeProperty("children", mydeviceChildren);
            collection.AppendObject(mydevicefolder);


            //additional attr
            JsonObject jo = new JsonObject();
            jo.MergeProperty("isMyDevice", new JsonConstant(true));
            foreach (var md in mydevices)
            {
                if (md.DeviceId != null)
                {
                    JsonObject d = new JsonObject();
                    d.MergeProperty("id", new JsonConstant(md.DeviceId));
                    d.MergeProperty("text", new JsonConstant(md.DeviceIP));
                    d.MergeProperty("attributes", jo);

                    if (md.HLevel != null && md.HLevel == 2)
                    {
                        d.MergeProperty("iconCls", new JsonConstant("icon-critical"));
                    }
                    else if (md.HLevel != null && md.HLevel == 1)
                    {
                        d.MergeProperty("iconCls", new JsonConstant("icon-warn"));
                    }
                    else
                    {
                        d.MergeProperty("iconCls", new JsonConstant("icon-normal"));
                    }
                    mydeviceChildren.AppendObject(d);
                }
            }

            if (sites.Count() == 0)
            {
                return RawJson(collection);
            }
            List<BusinessDeviceModel> bdevice = new List<BusinessDeviceModel>();
            var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);
            if (t.ID == 101)
            {
                if (USER_X.Department == "省局机关运维")
                {
                    bdevice = device.GetBusinessDeviceModel((int)t.ID);
                }
                else
                {
                    bdevice = device.GetBusinessDeviceModel(null);
                }
            }
            else
            {
                bdevice = device.GetBusinessDeviceModel((int)t.ID);
            }

            foreach (var onesite in bdevice.GroupBy(x => x.SiteName))
            {
                JsonObject s = new JsonObject();
                s.MergeProperty("text", new JsonConstant(onesite.Key));

                //bs collection
                JsonCollection bss = new JsonCollection();
                foreach (var onebs in onesite.GroupBy(x => x.BSId))
                {
                    //construct one bs
                    JsonObject b = new JsonObject();
                    b.MergeProperty("id", new JsonConstant(onebs.Key));
                    b.MergeProperty("text", new JsonConstant(onebs.First().BSName));
                    b.MergeProperty("iconCls", new JsonConstant("icon-applicatoin"));

                    //device collection
                    JsonCollection devices = new JsonCollection();
                    foreach (var onedevice in onebs)
                    {
                        if (onedevice.DeviceId != null)
                        {
                            JsonObject d = new JsonObject();
                            d.MergeProperty("id", new JsonConstant(onedevice.DeviceId));
                            d.MergeProperty("text", new JsonConstant(onedevice.DeviceIP));
                            if (onedevice.HLevel != null && onedevice.HLevel == 2)
                            {
                                d.MergeProperty("iconCls", new JsonConstant("icon-critical"));
                            }
                            else if (onedevice.HLevel != null && onedevice.HLevel == 1)
                            {
                                d.MergeProperty("iconCls", new JsonConstant("icon-warn"));
                            }
                            else
                            {
                                d.MergeProperty("iconCls", new JsonConstant("icon-normal"));
                            }
                            devices.AppendObject(d);
                        }
                    }

                    b.MergeProperty("children", devices);
                    //add to bss collection
                    bss.AppendObject(b);
                }


                s.MergeProperty("children", bss);
                collection.AppendObject(s);
            }



            return RawJson(collection);
        }

        [HttpPost]
        public ActionResult AddDevice(int DeviceId)
        {
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            MyDeviceModel model = new MyDeviceModel();
            model.DeviceId = (decimal)DeviceId;
            model.UserId = USER_X.ID;
            int returncount = device.AddMyDevice(model);
            if (returncount == 0)
                return new ContentResult() { Content = "设备已在我的设备列表中,不能重复添加!" };
            return new ContentResult() { Content = "添加成功,请刷新页面!" };
        }


        [HttpPost]
        public ActionResult RmDevice(int DeviceId)
        {
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            MyDeviceModel model = new MyDeviceModel();
            model.DeviceId = (decimal)DeviceId;
            model.UserId = USER_X.ID;
            int returncount = device.RemoveMyDevice(model);
            if (returncount == 1)
                return new ContentResult() { Content = "删除成功,请刷新页面!" };
            return new ContentResult() { Content = "错误!" };

        }

        public ActionResult GetPerformanceParametersByDeviceID(int DeviceID)
        {
            var parameters = performance.GetPerformanceParametersByDeviceID(DeviceID, null, null).Where(o => o.ParameterDisplay.Contains("CPU使用率") || o.ParameterDisplay.Contains("内存使用率"));

            JsonCollection collection = new JsonCollection();
            foreach (var p in parameters.GroupBy(x => x.ParameterDisplay))
            {
                JsonObject o = new JsonObject();
                o.MergeProperty("lable", new JsonConstant(p.Key));
                o.MergeProperty("value", new JsonConstant(p.Key));
                collection.AppendObject(o);
            }
            return RawJson(collection);

        }

        public ActionResult GetPerformanceByDeviceIDAndParameterDisplay(int DeviceID, string Param, DateTime? Start, DateTime? End)
        {
            List<string> listParam = new List<string>();
            if (!string.IsNullOrEmpty(Param))
            {
                string[] coms = Param.Split(',');
                foreach (var item in coms)
                {
                    if (string.IsNullOrWhiteSpace(item)) continue;
                    listParam.Add(item);
                }
            }

            JsonObject root = new JsonObject();
            //JsonCollection categories = new JsonCollection();
            JsonCollection series = new JsonCollection();
            foreach (var nParam in listParam)
            {
                JsonObject s = new JsonObject();
                s.MergeProperty("name", new JsonConstant(nParam));
                List<PerformanceModel> perf = null;
                if (Start == null && End == null)
                    perf = performance.GetPerformanceByDeviceIDAndParameterDisplay(DeviceID, nParam, DateTime.Now.AddMonths(-1), DateTime.Now);
                else
                    perf = performance.GetPerformanceByDeviceIDAndParameterDisplay(DeviceID, nParam, Start, End);
                JsonCollection sdata = new JsonCollection();
                s.MergeProperty("data", sdata);
                series.AppendObject(s);

                foreach (var p in perf.OrderBy(x => x.TimeStamp))
                {
                    //add unit
                    root.MergeProperty("unit", new JsonConstant(p.Unit));

                    //categories.AppendObject(new JsonConstant(p.TimeStamp));
                    JsonCollection onedata = new JsonCollection();

                    onedata.AppendObject(new JsonDateTime(p.TimeStamp));
                    decimal v = Convert.ToDecimal(p.Value);
                    //if (p.Unit == "%" && v < 1)
                    //{
                    //    v = v * 100;
                    //}
                    onedata.AppendObject(new JsonConstant(v));

                    sdata.AppendObject(onedata);
                }


            }
            root.MergeProperty("series", series);
            return RawJson(root);


        }


        public ActionResult GetAlertByDeviceId(int? DeviceId, int page, int rows, string sort, string order)
        {
            //get user info
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var sites = user_x.GetSiteBranchByID(USER_X.ID);
            var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);

            List<AlertDetailAndDevice> alerts = new List<AlertDetailAndDevice>();
            decimal total = 0;
            if (sites.Count > 0 && t != null)
            {
                if (t.ID == 101 && USER_X.Department != "省局机关运维")
                {

                    if (sort == null)
                        alerts = alert.GetAlertBySiteAndDeviceID(null, DeviceId, out total, rows, page);
                    else
                        alerts = alert.GetAlertBySiteAndDeviceID(null, DeviceId, out total, rows, page, sort, order == "desc" ? "Descending" : "Ascending");
                }
                else
                {
                    if (sort == null)
                        alerts = alert.GetAlertBySiteAndDeviceID(Convert.ToInt32(t.ID), DeviceId, out total, rows, page);
                    else
                        alerts = alert.GetAlertBySiteAndDeviceID(Convert.ToInt32(t.ID), DeviceId, out total, rows, page, sort, order == "desc" ? "Descending" : "Ascending");
                }
            }

            return Json(new _table
            {
                total = Convert.ToInt32(total),
                rows = alerts
            }, JsonRequestBehavior.AllowGet);

        }


        private class _table
        {
            public int total { get; set; }

            public List<AlertDetailAndDevice> rows { get; set; }
        }
    }
}
